package com.cari.oa.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.cari.oa.domain.SysModuleEntity;
import com.cari.oa.util.StrUtils;

/**
 * 系统模块DAO
 * User: yexuhui
 * Date: 12-12-18
 * Time: 下午5:18
 */
@SuppressWarnings("unchecked")
@Repository
public class SysModuleDao extends BaseDao<SysModuleEntity> {

    /**
     * 获取所有的顶级模块
     * @return 顶级模块实体列表
     */
    public List<SysModuleEntity> getAllTopModules() {
        String hql = "from SysModuleEntity m where m.parentId is null order by m.orderNum asc";
        Query query = getSession().createQuery(hql);
        return query.list();
    }
    
    /**
     * 获取用户关联的所有顶级模块
     * @param username 用户名
     * @return 顶级模块实体列表
     */
    public List<SysModuleEntity> getTopModulesByUser(String username) {
    	StringBuilder sb = new StringBuilder();
    	sb.append("   select distinct(m2.id) from SysUserRoleRelEntity ur, SysRoleActionRelEntity ra, SysActionEntity a, SysModuleEntity m1, SysModuleEntity m2 ");
    	sb.append("   where ur.userName = :username ");
    	sb.append("   and ur.roleName = ra.roleName ");
    	sb.append("   and ra.actionName = a.enname ");
    	sb.append("   and a.moduleName = m1.enname ");
    	sb.append("   and m1.parentId = m2.id ");   
    	
        Query query = getSession().createQuery(sb.toString());
        query.setString("username", username);
        List<Integer> ids = query.list();
        if(ids.size() == 0) return new ArrayList<SysModuleEntity>();
        System.out.println(username);
        System.out.println(ids);
    	
    	String hql = "from SysModuleEntity m where m.id in (:ids) order by m.orderNum asc";
    	query = getSession().createQuery(hql);
    	query.setParameterList("ids", ids);
        return query.list();
    }
    
    /**
     * 获取所有的子级模块
     * @return 子级模块实体列表
     */
    public List<SysModuleEntity> getAllSubModules() {
        String hql = "from SysModuleEntity m where m.parentId is not null order by m.enname asc";
        Query query = getSession().createQuery(hql);
        return query.list();
    }
    
    /**
     * 获取用户关联的所有子模块
     * @param username 用户名
     * @return 子模块实体列表
     */
    public List<SysModuleEntity> getSubModulesByUser(String username) {
    	StringBuilder sb = new StringBuilder();
    	sb.append("   select distinct(m.id) from SysUserRoleRelEntity ur, SysRoleActionRelEntity ra, SysActionEntity a, SysModuleEntity m ");
    	sb.append("   where ur.userName = :username ");
    	sb.append("   and ur.roleName = ra.roleName ");
    	sb.append("   and ra.actionName = a.enname ");
    	sb.append("   and a.moduleName = m.enname "); 
    	
        Query query = getSession().createQuery(sb.toString());
        query.setString("username", username);
        List<Integer> ids = query.list();
        if(ids.size() == 0) return new ArrayList<SysModuleEntity>();
    	
    	String hql = "from SysModuleEntity m where m.id in (:ids) order by m.orderNum asc ";
    	query = getSession().createQuery(hql);
    	query.setParameterList("ids", ids);
        return query.list();
    }    

    /**
     * 根据父模块ID获取所有的子模块实体
     * @param parentId 父模块ID
     * @return 子模块实体列表
     */
    public List<SysModuleEntity> getSubModulesByParentId(String parentId) {
        String hql = "from SysModuleEntity m where m.parentId = :parentid order by m.orderNum asc";
        Query query = getSession().createQuery(hql);
        query.setString("parentid", parentId);
        return query.list();
    }

    /**
     * 根据模块英文名获取模块
     * @param enname 模块英文名
     * @return 系统模块实体
     */
    public SysModuleEntity getModulesByEnname(String enname) {
        String hql = "from SysModuleEntity m where m.enname = :enname";
        Query query = getSession().createQuery(hql);
        query.setString("enname", enname);
        return (SysModuleEntity) query.uniqueResult();
    }

    /**
     * 根据模块英文名判断模块是否存在
     * @param enname 模块英文名
     * @return 是否存在
     */
    public boolean existByEnname(String enname) {
        Query query = getSession().createQuery("select count(*) from SysModuleEntity m where m.enname = :enname");
        query.setString("enname", enname);
        Long count = (Long)query.uniqueResult();
        return count > 0;
    }

    /**
     * 判断模块名是否被角色使用
     * @param enname 系统模块英文名
     * @return 是否被使用
     */
    public boolean isModuleUsedByRole(String enname) {
        String hql = "select count(*) from SysRoleActionRelEntity r, SysActionEntity a where a.moduleName = :enname and r.actionName = a.enname";
        Query query = getSession().createQuery(hql);
        query.setString("enname", enname);
        Long count = (Long)query.uniqueResult();
        return count > 0;
    }

    /**
     * 系统模块查询记录数
     * @param enname 系统模块英文名，可为空
     * @param alias 系统模块别名，可为空
     * @param parentId 父模块ID，可为空
     * @return 查询记录数
     */
    public long getCount(String enname, String alias, String parentId) {
        List<Object> params = new ArrayList<Object>();
        String hql = "select count(*) from SysModuleEntity m where 1=1 ";
        if(StrUtils.isNotEmpty(enname)) {
            hql += "and enname like ?";
            params.add("%" + enname + "%");
        }

        if(StrUtils.isNotEmpty(alias)) {
            hql += "and alias like ?";
            params.add("%" + alias + "%");
        }

        if(StrUtils.isNotEmpty(parentId)) {
            hql += "and parentId = ?";
            params.add(parentId);
        }

        Query query = getSession().createQuery(hql);
        for (int i = 0; i < params.size(); i++) {
            query.setParameter(i, params.get(i));
        }
        return (Long)query.uniqueResult();
    }

    /**
     * 系统模块分页查询
     * @param enname 系统模块英文名，可为空
     * @param alias 系统模块别名，可为空
     * @param parentId 父模块ID，可为空
     * @param page 当前第几页，不可为空
     * @param size 每页条数，不可为空
     * @return 系统模块分页记录
     */
    public List<SysModuleEntity> getPage(String enname, String alias, String parentId, int page, int size) {
        List<Object> params = new ArrayList<Object>();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("from SysModuleEntity m1 where 1=1 ");

        if(StrUtils.isNotEmpty(enname)) {
            stringBuilder.append("and m1.enname like ? ");
            params.add("%" + enname + "%");
        }

        if(StrUtils.isNotEmpty(alias)) {
            stringBuilder.append("and m1.alias like ? ");
            params.add("%" + alias + "%");
        }

        if(StrUtils.isNotEmpty(parentId)) {
            stringBuilder.append("and m1.parentId = ? ");
            params.add(parentId);
        }

        return getPage(stringBuilder.toString(), page, size, params.toArray());
    }
}
